package com.situ.vivamarket.controller.front;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.situ.vivamarket.model.Goods;
import com.situ.vivamarket.model.search.GoodsSearchBean;
import com.situ.vivamarket.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/vm/front/goods")
public class FrontGoodsController {
    GoodsService goodsService;

    //依赖注入
    @Autowired
    public void setGoodsService(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    //      跳转显示商品网格页面
    @GetMapping("/grid")
    public String goodsGrid(GoodsSearchBean gsb,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "12") Integer limit,
                            Map<String, Object> map) {
        if(page>100000||page<=0){
            page = 1;
        }
        if(limit>10000000||limit<=0){
            limit = 12;
        }

        List<Goods> goods = this.goodsService.getAllGoods(gsb, new Page<>(page, limit));
        map.put("goods", goods);
//        获取

        //        分页对象
        PageInfo<Goods> pi = new PageInfo<>(goods);
        //        设置5页
        pi.calcByNavigatePages(5);
        List<Integer> pages = new ArrayList<>();
        //        两个分别为获取的第一页和最后一页
        for (int i = pi.getNavigateFirstPage(); i <= pi.getNavigateLastPage(); i++) {
            pages.add(i);
        }
        map.put("pages", pages);
        map.put("pi", pi);
        map.put("gsb", gsb);

        return "front/goods/grid";
    }

    //      跳转商品详情页面
    @GetMapping("/detail")
    public String goodsDetail(Integer goodsId, Map<String, Object> map) {
        Goods goods = goodsService.findById(goodsId);
        map.put("goods", goods);
        return "front/goods/detail";
    }
    @GetMapping("/compare")
    public String goodsCompare(Integer catId,Map<String, Object> map) {
        if(catId==null||catId==0){
            catId=1;
        }
        List<Goods> goods=this.goodsService.findByCatId(catId,3);
//        没有就找全部种类
        if(goods==null||goods.size()==0){
            goods=this.goodsService.findByCatId(1,3);
        }
        map.put("goods", goods);
        return "front/goods/compare";
    }
}
